let audio = new Audio();

//引入 $store, 用于后续操作
import $store from '../store/index.js';
// import $request from './request.js';

audio.playSong = async function (id) {
	// let check_result = await $request(`/check/music?id=${id}`);
	
	audio.src = `https://music.163.com/song/media/outer/url?id=${id}.mp3`;
	console.log("进入播放");
	audio.oncanplay = function (){
		audio.play();
	}
}

audio.pauseSong = function() {
	audio.pause();
}

audio.addEventListener("playing", () => {
	console.log('播放中');
	$store.commit('change_state', true);
})

audio.addEventListener("pause", () => {
	$store.commit("change_state", false);
})
audio.addEventListener('timeupdate', () =>{
	
	// console.log(parseInt(audio.duration),(audio.currentTime.toFixed(3)*1000));
	if($store.state.timeupdate_switch){
		let song_duration_info = {
		duration: parseInt(audio.duration) ,
		current_time: parseInt(audio.currentTime) ,
	};
	$store.commit("set_song_duration_info", song_duration_info);
	$store.commit("lyric_play", audio.currentTime.toFixed(3)*1000);
	}
	
})
audio.addEventListener("ended", () => {
	// this.$root.$children[0].next_song;
	let nowidx = $store.state.song_idx + 1;
	if(nowidx == 10){
		nowidx = 0;
	}

	let playingsongs_id = $store.state.play_list[nowidx];
	//将vuex 内的 下标更新为 最新的下标
	$store.commit('change_idx', nowidx);
	// //拿到id 后进行歌曲播放, 并且更新歌曲详情
	audio.playSong(playingsongs_id);
	// //触发 action 更新 vuex 内的song_info
	$store.dispatch("get_song_detail", playingsongs_id);
	// // 用id 去请求 歌词 
	$store.dispatch('get_lyric', playingsongs_id);
	
})

export default audio;
